package com.sztx.worker_monitor.web.handle;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sztx.se.core.quartz.component.QuartzManager;
import com.sztx.se.core.quartz.config.JobRunningInfo;
import com.sztx.se.core.quartz.config.QuartzParameter;
import com.sztx.worker_monitor.common.DateStringUtils;
import com.sztx.worker_monitor.web.model.QuartzDetailModel;
import com.sztx.worker_monitor.web.model.QuartzModel;
import com.sztx.worker_monitor.web.model.ResultStatus;
import com.sztx.worker_monitor.web.model.SearchListModel;

@Component
public class QuartzHandle {
	protected static final Logger logger = LoggerFactory.getLogger(QuartzHandle.class);
	
	static public enum  MethodType{
		Restart,Delete,	Pause
	}
	
	@Autowired(required = false)
	private QuartzManager quartzManager;
	

	public QuartzHandle() {}

	
	public List<QuartzModel> getQuartzModelList(){
		
		if(quartzManager == null) {
			System.out.println("ERROR！getQuartzModelList reutn null， 因为 quartzManager 为null");
			return null;
			
		};
		
		List<QuartzModel> quartzModelList = null;
		try{
			List<QuartzParameter>  quartzParameterList  = 
					quartzManager.getAllJobs();
			quartzModelList = QuartzModel.changeToQuartzModelList(quartzParameterList);
			return quartzModelList;
		}catch(Exception e){
			e.printStackTrace();
			return quartzModelList;
			
		}	
	}
	
	public List<QuartzModel> getQuartzModelList(String keyTaskname, String keySchedname){

		if(quartzManager == null) {
			System.out.println("ERROR！getQuartzModelList reutn null， 因为 quartzManager 为null");
			return null;
			
		};
		if(keyTaskname==null ||"".equals(keyTaskname)){
			keyTaskname = "";
		}
		
		if(keySchedname==null ||"".equals(keySchedname)){
			keySchedname = "";
		}
		if(keyTaskname.length() == 0 && keySchedname.length() == 0)
			return getQuartzModelList();
		
		List<QuartzModel> quartzModelList = null;
		try{
			List<QuartzParameter>  quartzParameterList  = 
					quartzManager.getAllJobs();
			
			quartzModelList = new ArrayList<QuartzModel>();
			for(int i =0; i < quartzParameterList.size(); i ++){
				if(keyTaskname.length() != 0 && keySchedname.length() != 0){
					if(quartzParameterList.get(i).getJobName().indexOf(keyTaskname) != -1 &&
					   quartzParameterList.get(i).getSchedName().indexOf(keySchedname) != -1){
						QuartzModel quartzModel = new QuartzModel(quartzParameterList.get(i));
						quartzModelList.add(quartzModel);
					}
				}else if(keyTaskname.length() != 0){
					if(quartzParameterList.get(i).getJobName().indexOf(keyTaskname) != -1 ){
						QuartzModel quartzModel = new QuartzModel(quartzParameterList.get(i));
						quartzModelList.add(quartzModel);
					}
					
				}else{
					if(quartzParameterList.get(i).getSchedName().indexOf(keySchedname) != -1){
						QuartzModel quartzModel = new QuartzModel(quartzParameterList.get(i));
						quartzModelList.add(quartzModel);
					}
					
				}
				
			}
			return quartzModelList;
		}catch(Exception e){
			e.printStackTrace();
			return quartzModelList;
			
		}	
	}
	
	/*
	 * 操作一个job（重启，暂停，删除）,返回错误信息，没有错误返回null
	 * 
	 * */
	public String ctrlJob(
			MethodType methodType,
			String schedName,
			String triggerName,
			String triggerGroup,
			String jobName,
			String jobGroup){
	
		if(schedName == null || "".equals(schedName))
			return "计划名称错误";
		if(triggerName == null || "".equals(triggerName))
			return "触发器错误";
		if(triggerGroup == null || "".equals(triggerGroup))
			return "触发器组错误";
		if(jobName == null || "".equals(jobName))
			return "任务名称出错";
		if(jobGroup == null || "".equals(jobGroup))
			return "任务分组出错";
		
		//查询该job是否存在
		try{
			QuartzParameter quartzParameter=
					quartzManager.getJob(schedName, jobName, jobGroup, triggerName, triggerGroup);
			if(quartzParameter == null) return "该job不存在";
			switch(methodType){
			case Restart:
				quartzManager.resumeTrigger(schedName, triggerName, triggerGroup);
				break;
				
			case Delete:
				quartzManager.deleteTrigger(schedName, triggerName, triggerGroup);
				break;
				
			case Pause:
				quartzManager.pauseTrigger(schedName, triggerName, triggerGroup);
				break;
			default:
				return "内部错误";
			}
			
			return null;
			
		}catch(Exception e){
			e.printStackTrace();
			return "quartzManager操作出错："+e;
		}
	
	}

public String addNewJob(	
		String schedName,
		String jobName,
		String jobGroup,
		String jobClassName,
		String description,
		String isRecoveryStr,
		
		String triggerName,
		String triggerGroup,
		String isCronTriggerStr,
		String expression ){

	if(schedName == null || "".equals(schedName))
		return "缺少计划名称";
	if(jobName == null || "".equals(jobName))
		return "缺少job名称";
	if(jobGroup == null || "".equals(jobGroup))
		return "缺少任务分组名";
	if(jobClassName == null || "".equals(jobClassName))
		return "缺少执行class名";
	if(description == null)
		description = "";
	if(isRecoveryStr == null)
		isRecoveryStr = "true";
	if(triggerName == null || "".equals(triggerName))
		return "缺少触发器名称";
	if(triggerGroup == null || "".equals(triggerGroup))
		return "缺少触发器组名称";
	if(isCronTriggerStr == null || "".equals(isCronTriggerStr) )
		isCronTriggerStr= "true";
	if(expression == null || "".equals(expression) )
		return "缺少触发规则";
	
	Boolean isRecovery = Boolean.valueOf(isRecoveryStr);
	Boolean isCronTrigger =Boolean.valueOf(isCronTriggerStr);

	//查询该job是否存在
	try{
		QuartzParameter quartzParameter=
				quartzManager.getJob(schedName, jobName, jobGroup, triggerName, triggerGroup);
		if(quartzParameter != null) return "该job已经存在";
		logger.info("{}, {}, {} not exist, so just add it", schedName, jobName, jobGroup);
		
		Date now=new Date();
		Map<String, String> extraInfo = new HashMap<String, String>();
		extraInfo.put("createData", DateStringUtils.DateToStr(now));
		boolean result = quartzManager.saveJob(schedName, jobName, jobGroup, jobClassName, description, isRecovery, triggerName, triggerGroup, isCronTrigger,
				expression, null, null, extraInfo);
		
		logger.info("Create new job result is {}", result);
		return result ? null : "创建job失败！";
		
	}catch(Exception e){
		e.printStackTrace();
		return "quartzManager操作出错："+ e;
	}

}

	public QuartzModel getJobModel(String schedName,String jobName, String jobGroup,String triggerName,String triggerGroup){

	
		try{
			QuartzParameter quartzParameter =quartzManager.getJob(schedName, jobName, jobGroup, triggerName, triggerGroup);
			if(quartzParameter == null) return null;
			return new QuartzModel(quartzParameter);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		
		}
	}

	public String updateJob(String schedName,
			String jobName,
			String jobGroup,
			String jobClassName,
			String description,
			String isRecoveryStr,
			
			String triggerName,
			String triggerGroup,
			String isCronTriggerStr,
			String expression){
	
		if(schedName == null || "".equals(schedName))
			return "缺少计划名称";
		if(jobName == null || "".equals(jobName))
			return "缺少job名称";
		if(jobGroup == null || "".equals(jobGroup))
			return "缺少任务分组名";
		if(jobClassName == null || "".equals(jobClassName))
			return "缺少执行class名";
		if(description == null)
			description = "";
		if(isRecoveryStr == null)
			isRecoveryStr = "true";
		if(triggerName == null || "".equals(triggerName))
			return "缺少触发器名称";
		if(triggerGroup == null || "".equals(triggerGroup))
			return "缺少触发器组名称";
		if(isCronTriggerStr == null || "".equals(isCronTriggerStr) )
			isCronTriggerStr= "true";
		if(expression == null || "".equals(expression) )
			return "缺少触发规则";
		
		Boolean isRecovery = Boolean.valueOf(isRecoveryStr);
		Boolean isCronTrigger =Boolean.valueOf(isCronTriggerStr);

		//查询该job是否存在
		try{

			Date now=new Date();
			Map<String, String> extraInfo = new HashMap<String, String>();
			extraInfo.put("createData", DateStringUtils.DateToStr(now));
			quartzManager.updateJob(schedName, jobName, jobGroup, jobClassName, description, isRecovery, triggerName, triggerGroup, isCronTrigger,
					expression, null, null, extraInfo);
			return null;
			
		}catch(Exception e){
			e.printStackTrace();
			return "quartzManager操作出错："+ e;
		}

	}
	
	
	public SearchListModel getSearchList(){

		List<QuartzModel> quartzModels = getQuartzModelList();
		 
		return new SearchListModel(quartzModels); 

	}
	
	public ResultStatus getJobDetail(
			String schedName, 
			String jobName, 
			String jobGroup, 
			String triggerName,
			String triggerGroup){

		logger.info("getJobDetail=>schedName="+schedName + 
				",jobName="+jobName+
				",jobGroup="+jobGroup+
				",triggerName="+triggerName+
				",triggerName="+triggerName+
				",triggerGroup="+triggerGroup);
		
		if(schedName == null || "".equals(schedName))
			return new ResultStatus("缺少计划名称");
		if(jobName == null || "".equals(jobName))
			return new ResultStatus("缺少job名称");
		if(jobGroup == null || "".equals(jobGroup))
			return new ResultStatus("缺少任务分组名");
		if(triggerName == null || "".equals(triggerName))
			return new ResultStatus("缺少触发器名称");
		if(triggerGroup == null || "".equals(triggerGroup))
			return new ResultStatus("缺少触发器组名称");
		
		try{
			QuartzParameter quartzParameter = quartzManager.getJob(
					schedName,  
					jobName,  
					jobGroup,  
					triggerName, 
					triggerGroup);
			if(quartzParameter == null ){
				return new ResultStatus("quartzParameter == null");
			}
			JobRunningInfo jobRunningInfo = quartzManager.getJobRunningInfo(
					schedName, 
					jobName, 
					jobGroup);
			
			QuartzDetailModel quartzDetailModel = new QuartzDetailModel(quartzParameter, jobRunningInfo);
			return new ResultStatus("", true, quartzDetailModel);
			
		}catch(Exception e){
			e.printStackTrace();
			return new ResultStatus("quartzManager操作出错："+ e);
		}

	}
	
	
}
